package com.bay1ts.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.cache.NullUserCache;
import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
/**
 * @author bay1ts
 * 没有验证密码是否正确啊！！一会重写！
 * 2015/10/25/18:08
 */
public class CustomJdbcDaoImpl extends JdbcUserDetailsManager {
	@Autowired
	private SaltSource saltSource;
	@Autowired
	private PasswordEncoder passwordEncoder;
	private UserCache userCache = new NullUserCache();
	@Override
	public void changePassword(String oldPassword, String newPassword) throws AuthenticationException {
		Authentication currentUser = SecurityContextHolder.getContext()
				.getAuthentication();
		

		if (currentUser == null) {
			// This would indicate bad coding somewhere
			throw new AccessDeniedException(
					"Can't change password as no Authentication object found in context "
							+ "for current user.");
		}

		String username = currentUser.getName();
		
		//以上部分为原实现

		UserDetails user=loadUserByUsername(username);
		String encodedOldPassword=passwordEncoder.encodePassword(oldPassword,saltSource.getSalt(user));
		String encodedPassword=passwordEncoder.encodePassword(newPassword,saltSource.getSalt(user));
		String oldPasswordFromDb=getJdbcTemplate().queryForObject("SELECT PASSWORD FROM USERS WHERE USERNAME=?", new Object[] {username},String.class);
		if(oldPasswordFromDb.equals(encodedOldPassword)){
			getJdbcTemplate().update("UPDATE USERS SET PASSWORD = ? WHERE USERNAME = ?",encodedPassword, username);
			
			//以下部分为原实现
			SecurityContextHolder.getContext().setAuthentication(
					createNewAuthentication(currentUser, encodedPassword));

			userCache.removeUserFromCache(username);
		}else{
			throw new AccessDeniedException(
					"Can't change password as no Authentication object found in context "
							+ "for current user.");
		}
	}

}
